package com.ztomorrow.ying_cun_plus.auth;

import com.ztomorrow.ying_cun_plus.constant.front.ErrorCodeEnum;
import com.ztomorrow.ying_cun_plus.constant.front.SystemConstant;
import com.ztomorrow.ying_cun_plus.dto.UserInfoDto;
import com.ztomorrow.ying_cun_plus.exception.BusinessException;
import com.ztomorrow.ying_cun_plus.service.impl.UserServiceImpl;
import com.ztomorrow.ying_cun_plus.utils.JWTUtils;
import org.springframework.util.StringUtils;

import java.util.Objects;

public interface AuthStrategy {

    void auth(String token, String requestUri) throws BusinessException;

    default Long authSSO(UserServiceImpl userInfoCacheManager,
                         String token) {
        if (!StringUtils.hasText(token)) {
            // token 为空
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        Long userId = JWTUtils.verifyJWT(token, SystemConstant.NOVEL_FRONT_KEY);
        if (Objects.isNull(userId)) {
            // token 解析失败
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        UserInfoDto userInfo = userInfoCacheManager.getUser(userId);
        if (Objects.isNull(userInfo)) {
            // 用户不存在
            throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_NOT_EXIST);
        }
        // 设置 userId 到当前线程
        UserHolder.setUserId(userId);
        // 返回 userId
        return userId;
    }
}
